package net.qiqb.core.domain.event.receiver;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassLoaderUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import net.qiqb.core.domain.event.DomainEvent;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DomainEventModuleServiceImpl implements DomainEventModuleService {

    @Autowired
    private DomainEventMulticaster domainEventMulticaster;

    @Override
    public List<ReceiveAckResp> receive(String domainEventClassName, byte[] bytes) {
        boolean hasListener = false;
        try {
            // 如果能加载，就标识引用了此事件的api，后面判断是否监听
            ClassLoaderUtil.loadClass(domainEventClassName);
            hasListener = true;
        } catch (Exception e) {
            log.warn("找不到领域对象类：" + domainEventClassName);
        }
        if (hasListener) {
            final DomainEvent domainEvent = ObjectUtil.deserialize(bytes);
            // 扫描 应用中是否有监听器监听领域事件
            final int qty = domainEventMulticaster.findAndMulticastEvent(domainEvent);

            final List<ReceiveAckResp> serverAckResps = CollUtil.toList(new ReceiveAckResp(qty, "127.0.0.1"));
            return serverAckResps;
        }

        return new ArrayList<>();
    }
}
